package com.warren.service.impl.py;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.warren.dao.py.TRsOrderMapper;
import com.warren.dao.py.TWechatUserMapper;
import com.warren.entity.py.TRsOrder;
import com.warren.entity.py.TWechatUser;
import com.warren.service.py.DownJsonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

/**
 * @version V1.0
 * @Description:
 * @author: warren
 * @date: 2022/7/27$ 13:39$
 */
@Service
public class DownJsonServiceImpl implements DownJsonService {
    @Autowired
    TWechatUserMapper tWechatUserMapper;

    @Autowired
    TRsOrderMapper tRsOrderMapper;
    /**
     * BBR正式导客关系最终
     */
    @Override
    public void downWechatUser() {
        List<TWechatUser> tWechatUsers = tWechatUserMapper.selectAllDetail();
        //toJSONString会去掉为null的字段，所以需要加序列号器
        String json = JSON.toJSONString(tWechatUsers, SerializerFeature.WriteMapNullValue,SerializerFeature.WriteNullStringAsEmpty,SerializerFeature.WriteNullNumberAsZero);
//        System.out.println(json);
        String filename = "D:\\nike\\hello-world\\src\\main\\resources\\BBR正式导客关系最终.json";
        //将json字符串写入到json文件中
        toJsonFile(json, filename);
    }

    @Override
    public void downOrderDetail() {
        List<TRsOrder> orders = tRsOrderMapper.selectAllDetail();
        String json = JSON.toJSONString(orders, SerializerFeature.WriteMapNullValue,SerializerFeature.WriteNullStringAsEmpty,SerializerFeature.WriteNullNumberAsZero);
        String filename = "D:\\nike\\hello-world\\src\\main\\resources\\BBR正式合并订单数据最终.json";
        //将json字符串写入到json文件中
        toJsonFile(json, filename);
    }

    /**
     * json转换为文件
     * @param json
     * @param filename
     */
    private void toJsonFile(String json, String filename) {
        FileWriter fw = null;
        BufferedWriter bw = null;
        try {
            fw = new FileWriter(new File(filename));
            bw = new BufferedWriter(fw);
            bw.write(json);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bw.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
